#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <assert.h>

#include "utility.h"


int main(int argc, char *argv[])
{
    // 打开文件
    int fd = open(SHR_STRU, O_RDWR|O_CREAT,0777);
    UTIL_ASSERT(fd!=-1);

    // 获取设置文件大小
    off_t pageSize = sysconf(_SC_PAGE_SIZE);
    off_t length = sizeof(SHARE_HEAD);
    length = (length+pageSize-1) & ~(pageSize - 1);
    int ret = ftruncate(fd, length); /* To obtain file size */
    UTIL_ASSERT(ret!=-1);

    // 映射结构体
    volatile SHARE_HEAD *pHead = (volatile SHARE_HEAD *)mmap(NULL, length, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    assert(pHead != MAP_FAILED);
    close(fd);

    // 初始化头
    pHead->ridx = 0;
    pHead->widx = 0;
    pHead->totalLen = SHR_BUF_LEN;

    // 映射地址
    fd = open(SHR_FILE_BUF, O_RDWR|O_CREAT,0777);
    assert(fd != -1);
    ret = ftruncate(fd, SHR_BUF_LEN); /* To obtain file size */
    assert(ret != -1);
    pHead->pAddr2 = (volatile char *)mmap(NULL, SHR_BUF_LEN, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    assert(pHead->pAddr2 != NULL);
    close(fd);

    // 写数据到共享缓冲区
    memset((void *)pHead->pAddr2,'c',SHR_BUF_LEN);
    pHead->widx += SHR_BUF_LEN-1;

    while(!pHead->ridx){
        printf("%s#%d,waiting read\n",__FUNCTION__,__LINE__);
        sleep(1);
    }
    return 0;
}
